<template>
  <div id="app">
      <h4>第八题</h4>
    <div>
      <span>姓名:</span>
      <input type="text" v-model="uname" />
    </div>
    <div>
      <span>年龄:</span>
      <input type="number" v-model="age" />
    </div>
    <div>
      <span>性别:</span>
      <select v-model="sex">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button @click="add">添加/修改</button>
    </div>
    <div>
      <table
        border="1"
        cellpadding="10"
        cellspacing="0"
      >
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="(obj,index) in arr" :key="index">
          <td>{{ index +1 }}</td>
          <td>{{ obj.uname }}</td>
          <td>{{ obj.age }}</td>
          <td>{{ obj.sex }}</td>
          <td>
            <button @click="dlt(index)" >删除</button>
            <button @click="red(index)" >编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>

<script>
export default {
  data () {
    return {
      arr: [],
      uname: '',
      age: 0,
      sex: '',
      isRed: false,
      index: null
    }
  },
  methods: {
    add () {
      if (this.isRed) {
        this.arr[this.index].uname = this.uname
        this.arr[this.index].age = this.age
        this.arr[this.index].sex = this.sex
        this.uname = this.age = this.sex = ''
        this.isRed = false
        return
      } else if (!this.uname || !this.age || !this.sex) return alert('请填写信息')
      this.arr.push({
        uname: this.uname,
        age: this.age,
        sex: this.sex
      })
      this.uname = this.age = ''
    },
    dlt (i) {
      this.arr.splice(i, 1)
    },
    red (i) {
      this.isRed = true
      this.index = i
      this.uname = this.arr[i].uname
      this.age = this.arr[i].age
      this.sex = this.arr[i].sex
    }
  }
}
</script>

<style>

</style>
